package net.xdclass.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.OSSConfig;
import net.xdclass.service.FileService;
import net.xdclass.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.regex.Pattern;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

	@Autowired
	private OSSConfig ossConfig;

	@Override
	public String uploadUserImg(MultipartFile file) {
		String accessKeyId = ossConfig.getAccessKeyId();
		String accessKeySecret = ossConfig.getAccessKeySecret();
		String endPoint = ossConfig.getEndPoint();
		String bucketname = ossConfig.getBucketname();
		OSS ossClient = new OSSClientBuilder().build(endPoint,accessKeyId,accessKeySecret);
		String originalFilename = file.getOriginalFilename();
		LocalDateTime ldt = LocalDateTime.now();
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
		String foder = dateTimeFormatter.format(ldt);
		String uuid = CommonUtil.generateUUID();
		String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

		String newFilename = foder + "/" + uuid + extension;
		try{
			PutObjectResult putObjectResult = ossClient.putObject(bucketname,newFilename,file.getInputStream());
			if (putObjectResult != null ){
				 String imgUrl = "https://"+bucketname+"."+endPoint+"/"+newFilename;
				 return  imgUrl;
			}
		}
		catch(Exception e ){
			log.error("上传文件失败：{}",e.getMessage());
		}finally {
			ossClient.shutdown();
		}
        return  null;
	}
}
